"""
数据对比服务
用于比较页面数据和数据库数据的差异
"""
from typing import Dict, List, Any
from app.models import Organization, Employee
from app.utils.data_collector import DataCollector

class ComparisonService:
    """数据对比服务类"""
    
    def __init__(self):
        self.data_collector = DataCollector()
    
    def compare_organization_data(self) -> Dict[str, Any]:
        """比较组织数据差异"""
        # 获取页面数据
        page_data = self.data_collector.get_organization_data()
        
        # 获取数据库数据
        db_org = Organization.query.first()
        if not db_org:
            return {"error": "数据库中未找到组织数据"}
        
        db_data = db_org.to_dict()
        
        # 计算差异
        differences = []
        field_mappings = {
            "total_employees": "总人数",
            "formal_employees": "正式工总人数",
            "gender_ratio": "男女比例",
            "avg_age": "平均年龄",
            "avg_tenure": "平均司龄",
            "management_positions": "管理岗人数",
            "reporting_depth": "平均汇报深度",
            "management_span": "平均管理幅度",
            "probation_count": "试用期人数",
            "party_member_ratio": "党员比例",
            "campus_recruit_ratio": "校招生比例",
            "new_employee_ratio": "近一年新员工比例",
            "turnover_rate": "近一年离职率",
            "officer_soldier_ratio": "官兵比"
        }
        
        for field, display_name in field_mappings.items():
            page_value = page_data["organization"].get(field)
            db_value = db_data.get(field)
            
            # 处理None值
            page_value = str(page_value) if page_value is not None else ''
            db_value = str(db_value) if db_value is not None else ''
            
            # 添加所有字段进行对比，不管是否相同
            differences.append({
                "field": display_name,
                "field_name": field,
                "page_value": page_value.strip(),
                "db_value": db_value.strip(),
                "location": "组织画像",
                "database": "tds_standard.organizations"
            })
        
        return {
            "differences": differences,
            "page_data": page_data,
            "db_data": db_data
        }
    
    def compare_employee_data(self) -> Dict[str, Any]:
        """比较员工数据差异"""
        # 获取页面数据
        page_employees = self.data_collector.get_employee_list()
        
        # 获取数据库数据
        db_employees = Employee.query.all()
        db_emp_dict = {emp.name: emp.to_dict() for emp in db_employees}
        
        # 计算差异
        differences = []
        field_mappings = {
            "department": "部门名称",
            "position": "岗位名称",
            "title": "职务",
            "level": "职级",
            "tags": "关键标签"
        }
        
        for page_emp in page_employees:
            emp_name = page_emp["name"]
            if emp_name in db_emp_dict:
                db_emp = db_emp_dict[emp_name]
                for field, display_name in field_mappings.items():
                    page_value = page_emp.get(field)
                    db_value = db_emp.get(field)
                    
                    # 处理None值和列表值
                    if isinstance(page_value, list):
                        page_value = ','.join(sorted(page_value))
                    if isinstance(db_value, str) and ',' in db_value:
                        db_value = ','.join(sorted(db_value.split(',')))
                    
                    page_value = str(page_value) if page_value is not None else ''
                    db_value = str(db_value) if db_value is not None else ''
                    
                    # 添加所有字段进行对比，不管是否相同
                    differences.append({
                        "field": display_name,
                        "field_name": field,
                        "page_value": page_value.strip(),
                        "db_value": db_value.strip(),
                        "employee": emp_name,
                        "location": "人才画像",
                        "database": "tds_standard.employees"
                    })
        
        return {
            "differences": differences,
            "page_data": page_employees,
            "db_data": [emp.to_dict() for emp in db_employees]
        }
    
    def get_all_differences(self) -> Dict[str, Any]:
        """获取所有数据差异"""
        org_diff = self.compare_organization_data()
        emp_diff = self.compare_employee_data()
        
        return {
            "organization_differences": org_diff["differences"],
            "employee_differences": emp_diff["differences"],
            "total_differences": len(org_diff["differences"]) + len(emp_diff["differences"])
        }
